package cn.good.biz.controller;

import cn.good.biz.config.FileConfig;
import cn.good.biz.service.ImagesService;
import cn.good.dto.Dto;
import cn.good.dto.DtoUtil;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.List;

/**
 * 文件上传类
 */
@Controller
@RequestMapping("/doc/file")
public class FileUploadController {

    private static final Logger logger = LoggerFactory.getLogger(FileUploadController.class);


    @Resource
    private FileConfig fileConfig;
    @Resource
    private ImagesService imagesService;

    /**
     * 单文件上传
     *
     * @param file
     * @param request
     * @return
     */
    @ResponseBody
    @PostMapping(value="/upload/{type}",headers="content-type=multipart/form-data")
    public Dto upload(@ApiParam(value="短视频",required=true)
        @RequestParam("file") MultipartFile file, HttpServletRequest request,Long id, @PathVariable Integer type) {
        //判断文件是否为空
        if (!file.isEmpty()) {
            //获取上传文件的路径
            String saveFileName = file.getOriginalFilename();
            // 获取文件名
            String fileName = file.getOriginalFilename();
            logger.info("上传的文件名为：" + fileName);
            // 获取文件的后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            logger.info("上传的后缀名为：" + suffixName);
            // 文件上传后的路径
            //String filePath = "E://test//";
            // 解决中文问题，liunx下中文路径，图片显示问题
            // fileName = UUID.randomUUID() + suffixName;
            //File dest = new File(filePath + fileName);
            //设置文件的保存路径
            System.out.println(suffixName);
            if (!suffixName.equalsIgnoreCase(".jpg")
                    && !suffixName.equalsIgnoreCase(".png")
                    && !suffixName.equalsIgnoreCase(".jpeg")
                    && !suffixName.equalsIgnoreCase(".pneg")
            ){
                return DtoUtil.returnFail("文件格式错误","30004");
            }
            //新文件名
            String newName = System.currentTimeMillis()+fileName;

            File saveFile = new File(fileConfig.getFileUploadPath() + newName);
            //判断文件是否存在 没有的话 就创建
            if (!saveFile.getParentFile().exists()) {
                saveFile.getParentFile().mkdirs();
            }
            try {
                //上传文件方法
                //file.transferTo(saveFile);

                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(saveFile));
                out.write(file.getBytes());
                out.flush();
                out.close();
                //保存上传的图片信息 或者区分         文件路径                              图片类型  关联id 用户id
                //imagesService.saveImage(fileConfig.getFileUploadPath() + newName,type,id,1L);

                return DtoUtil.returnSuccess("文件上传成功!");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return DtoUtil.returnFail("上传失败," + e.getMessage(),"30001");
            } catch (IOException e) {
                e.printStackTrace();
                return DtoUtil.returnFail("上传失败," + e.getMessage(),"30002");
            } catch (Exception e) {
                e.printStackTrace();
                return DtoUtil.returnFail("保存失败," + e.getMessage(),"30002");
            }
        } else {
            return DtoUtil.returnFail("上传失败，因为文件为空.","30003");
        }
    }

    /**
     * 多文件上传
     *
     * @param request
     * @return
     */
    @PostMapping("/uploadFiles")
    @ResponseBody
    public String uploadFiles(HttpServletRequest request) throws IOException {
        File savePath = new File(request.getSession().getServletContext().getRealPath("/upload/"));
        if (!savePath.exists()) {
            savePath.mkdirs();
        }
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            if (!file.isEmpty()) {
                try {
                    byte[] bytes = file.getBytes();
                    File saveFile = new File(savePath, file.getOriginalFilename());
                    stream = new BufferedOutputStream(new FileOutputStream(saveFile));
                    stream.write(bytes);
                    stream.close();
                } catch (Exception e) {
                    if (stream != null) {
                        stream.close();
                        stream = null;
                    }
                    return "第 " + i + " 个文件上传有错误" + e.getMessage();
                }
            } else {
                return "第 " + i + " 个文件为空";
            }
        }
        return "所有文件上传成功";
    }

}
